{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Person Tracking with OpenVINO™\n",
    "\n",
    "This notebook demonstrates live person tracking with OpenVINO: it reads frames from an input video sequence, detects people in the frames, uniquely identifies each one of them and tracks all of them until they leave the frame. We will use the [Deep SORT](https://arxiv.org/abs/1703.07402) algorithm to perform object tracking, an extension to SORT (Simple Online and Realtime Tracking).\n",
    "\n",
    "## Detection vs Tracking\n",
    "- In object detection, we detect an object in a frame, put a bounding box or a mask around it, and classify the object. Note that, the job of the detector ends here. It processes each frame independently and identifies numerous objects in that particular frame. \n",
    "- An object tracker on the other hand needs to track a particular object across the entire video. If the detector detects three cars in the frame, the object tracker has to identify the three separate detections and needs to track it across the subsequent frames (with the help of a unique ID).\n",
    "\n",
    "## Deep SORT\n",
    "[Deep SORT](https://arxiv.org/abs/1703.07402) can be defined as the tracking algorithm which tracks objects not only based on the velocity and motion of the object but also the appearance of the object.\n",
    "It is made of three key components which are as follows:\n",
    "![deepsort](https://user-images.githubusercontent.com/91237924/221744683-0042eff8-2c41-43b8-b3ad-b5929bafb60b.png)\n",
    "\n",
    "1. **Detection**\n",
    "\n",
    "   This is the first step in the tracking module. In this step, a deep learning model will be used to detect the objects in the frame that are to be tracked. These detections are then passed on to the next step.\n",
    "\n",
    "2. **Prediction**\n",
    "   \n",
    "   In this step, we use Kalman filter \\[1\\] framework to predict a target bounding box of each tracking object in the next frame. There are two states of prediction output: ```confirmed``` and ```unconfirmed```. A new track comes with a state of ```unconfirmed``` by default, and it can be turned into ```confirmed``` when a certain number of consecutive detections are matched with this new track. Meanwhile, if a matched track is missed over a specific time, it will be deleted as well.\n",
    "\n",
    "3. **Data association and update**\n",
    "   \n",
    "   Now, we have to match the target bounding box with the detected bounding box, and update track identities. A conventional way to solve the association between the predicted Kalman states and newly arrived measurements is to build an assignment problem with the Hungarian algorithm \\[2\\]. In this problem formulation, we integrate motion and appearance information through a combination of two appropriate metrics. The cost used for the first matching step is set as a combination of the Mahalanobis and the cosine distances. The [Mahalanobis distance](https://en.wikipedia.org/wiki/Mahalanobis_distance) is used to incorporate motion information and the cosine distance is used to calculate similarity between two objects. Cosine distance is a metric that helps the tracker recover identities in case of long-term occlusion and motion estimation also fails. For this purposes, a reidentification model will be implemented to produce a vector in high-dimensional space that represents the appearance of the object. Using these simple things can make the tracker even more powerful and accurate.\n",
    "\n",
    "   In the second matching stage, we will run intersection over union(IOU) association as proposed in the original SORT algorithm \\[3\\] on the set of unconfirmed and unmatched tracks from the previous step. If the IOU of detection and target is less than a certain threshold value called `IOUmin` then that assignment is rejected. This helps to account for sudden appearance changes, for example, due to partial occlusion with static scene geometry, and to increase robustness against erroneous.\n",
    "   \n",
    "   When detection result is associated with a target, the detected bounding box is used to update the target state.\n",
    "\n",
    "---\n",
    "\n",
    "\\[1\\] R. Kalman, \"A New Approach to Linear Filtering and Prediction Problems\", Journal of Basic Engineering, vol. 82, no. Series D, pp. 35-45, 1960.\n",
    "\n",
    "\\[2\\] H. W. Kuhn, \"The Hungarian method for the assignment problem\", Naval Research Logistics Quarterly, vol. 2, pp. 83-97, 1955.\n",
    "\n",
    "\\[3\\] A. Bewley, G. Zongyuan, F. Ramos, and B. Upcroft, “Simple online and realtime tracking,” in ICIP, 2016, pp. 3464–3468.\n",
    "\n",
    "<img referrerpolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=5b5a4db0-7875-4bfb-bdbd-01698b5b1a77&file=notebooks/person-tracking-webcam/person-tracking.ipynb\" />\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Imports](#Imports)\n",
    "- [Download the Model](#Download-the-Model)\n",
    "- [Load model](#Load-model)\n",
    "    - [Select inference device](#Select-inference-device)\n",
    "- [Data Processing](#Data-Processing)\n",
    "- [Test person reidentification model](#Test-person-reidentification-model)\n",
    "    - [Visualize data](#Visualize-data)\n",
    "    - [Compare two persons](#Compare-two-persons)\n",
    "- [Main Processing Function](#Main-Processing-Function)\n",
    "- [Run](#Run)\n",
    "    - [Initialize tracker](#Initialize-tracker)\n",
    "    - [Run Live Person Tracking](#Run-Live-Person-Tracking)\n",
    "\n",
    "\n",
    "### Installation Instructions\n",
    "\n",
    "This is a self-contained example that relies solely on its own code.\n",
    "\n",
    "We recommend  running the notebook in a virtual environment. You only need a Jupyter server to start.\n",
    "For details, please refer to [Installation Guide](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/README.md#-installation-guide)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -q \"openvino>=2024.0.0\"\n",
    "%pip install -q opencv-python requests scipy tqdm \"matplotlib>=3.4\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "from pathlib import Path\n",
    "import time\n",
    "\n",
    "import numpy as np\n",
    "import cv2\n",
    "from IPython import display\n",
    "import matplotlib.pyplot as plt\n",
    "import openvino as ov"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import local modules\n",
    "import requests\n",
    "\n",
    "if not Path(\"./notebook_utils.py\").exists():\n",
    "    # Fetch `notebook_utils` module\n",
    "\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
    "    )\n",
    "\n",
    "    open(\"notebook_utils.py\", \"w\").write(r.text)\n",
    "\n",
    "import notebook_utils as utils\n",
    "from deepsort_utils.tracker import Tracker\n",
    "from deepsort_utils.nn_matching import NearestNeighborDistanceMetric\n",
    "from deepsort_utils.detection import (\n",
    "    Detection,\n",
    "    compute_color_for_labels,\n",
    "    xywh_to_xyxy,\n",
    "    xywh_to_tlwh,\n",
    "    tlwh_to_xyxy,\n",
    ")\n",
    "\n",
    "# Read more about telemetry collection at https://github.com/openvinotoolkit/openvino_notebooks?tab=readme-ov-file#-telemetry\n",
    "from notebook_utils import collect_telemetry\n",
    "\n",
    "collect_telemetry(\"person-tracking.ipynb\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download the Model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "We will use pre-trained models from OpenVINO's [Open Model Zoo](https://docs.openvino.ai/2024/documentation/legacy-features/model-zoo.html) to start the test.\n",
    "\n",
    "In this case, [person detection model]( https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/intel/person-detection-0202/README.md) is deployed to detect the person in each frame of the video, and [reidentification model]( https://github.com/openvinotoolkit/open_model_zoo/blob/master/models/intel/person-reidentification-retail-0287/README.md) is used to output embedding vector to match a pair of images of a person by the cosine distance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from notebook_utils import download_ir_model\n",
    "\n",
    "# A directory where the model will be downloaded.\n",
    "base_model_dir = \"model\"\n",
    "precision = \"FP16\"\n",
    "# The name of the model from Open Model Zoo\n",
    "detection_model_name = \"person-detection-0202\"\n",
    "download_det_model_url = (\n",
    "    f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/2023.0/models_bin/1/{detection_model_name}/{precision}/{detection_model_name}.xml\"\n",
    ")\n",
    "detection_model_path = Path(base_model_dir) / detection_model_name / precision / f\"{detection_model_name}.xml\"\n",
    "\n",
    "if not detection_model_path.exists():\n",
    "\n",
    "    download_ir_model(download_det_model_url, Path(base_model_dir) / detection_model_name / precision)\n",
    "\n",
    "reidentification_model_name = \"person-reidentification-retail-0287\"\n",
    "download_reid_model_url = f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/2023.0/models_bin/1/{reidentification_model_name}/{precision}/{reidentification_model_name}.xml\"\n",
    "reidentification_model_path = Path(base_model_dir) / reidentification_model_name / precision / f\"{reidentification_model_name}.xml\"\n",
    "\n",
    "if not reidentification_model_path.exists():\n",
    "    download_ir_model(download_reid_model_url, Path(base_model_dir) / reidentification_model_name / precision)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Define a common class for model loading and predicting.\n",
    "\n",
    "There are four main steps for OpenVINO model initialization, and they are required to run for only once before inference loop.\n",
    " 1. Initialize OpenVINO Runtime.\n",
    " 2. Read the network from `*.bin` and `*.xml` files (weights and architecture).\n",
    " 3. Compile the model for device.\n",
    " 4. Get input and output names of nodes.\n",
    "\n",
    "In this case, we can put them all in a class constructor function.\n",
    "\n",
    "To let OpenVINO automatically select the best device for inference just use `AUTO`. In most cases, the best device to use is `GPU` (better performance, but slightly longer startup time)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "core = ov.Core()\n",
    "\n",
    "\n",
    "class Model:\n",
    "    \"\"\"\n",
    "    This class represents a OpenVINO model object.\n",
    "\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, model_path, batchsize=1, device=\"AUTO\"):\n",
    "        \"\"\"\n",
    "        Initialize the model object\n",
    "\n",
    "        Parameters\n",
    "        ----------\n",
    "        model_path: path of inference model\n",
    "        batchsize: batch size of input data\n",
    "        device: device used to run inference\n",
    "        \"\"\"\n",
    "        self.model = core.read_model(model=model_path)\n",
    "        self.input_layer = self.model.input(0)\n",
    "        self.input_shape = self.input_layer.shape\n",
    "        self.height = self.input_shape[2]\n",
    "        self.width = self.input_shape[3]\n",
    "\n",
    "        for layer in self.model.inputs:\n",
    "            input_shape = layer.partial_shape\n",
    "            input_shape[0] = batchsize\n",
    "            self.model.reshape({layer: input_shape})\n",
    "        self.compiled_model = core.compile_model(model=self.model, device_name=device)\n",
    "        self.output_layer = self.compiled_model.output(0)\n",
    "\n",
    "    def predict(self, input):\n",
    "        \"\"\"\n",
    "        Run inference\n",
    "\n",
    "        Parameters\n",
    "        ----------\n",
    "        input: array of input data\n",
    "        \"\"\"\n",
    "        result = self.compiled_model(input)[self.output_layer]\n",
    "        return result"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Select inference device\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "select device from dropdown list for running inference using OpenVINO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = utils.device_widget()\n",
    "\n",
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "detector = Model(detection_model_path, device=device.value)\n",
    "# since the number of detection object is uncertain, the input batch size of reid model should be dynamic\n",
    "extractor = Model(reidentification_model_path, -1, device.value)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Processing\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Data Processing includes data preprocess and postprocess functions.\n",
    "- Data preprocess function is used to change the layout and shape of input data, according to requirement of the network input format.\n",
    "- Data postprocess function is used to extract the useful information from network's original output and visualize it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess(frame, height, width):\n",
    "    \"\"\"\n",
    "    Preprocess a single image\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    frame: input frame\n",
    "    height: height of model input data\n",
    "    width: width of model input data\n",
    "    \"\"\"\n",
    "    resized_image = cv2.resize(frame, (width, height))\n",
    "    resized_image = resized_image.transpose((2, 0, 1))\n",
    "    input_image = np.expand_dims(resized_image, axis=0).astype(np.float32)\n",
    "    return input_image\n",
    "\n",
    "\n",
    "def batch_preprocess(img_crops, height, width):\n",
    "    \"\"\"\n",
    "    Preprocess batched images\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    img_crops: batched input images\n",
    "    height: height of model input data\n",
    "    width: width of model input data\n",
    "    \"\"\"\n",
    "    img_batch = np.concatenate([preprocess(img, height, width) for img in img_crops], axis=0)\n",
    "    return img_batch\n",
    "\n",
    "\n",
    "def process_results(h, w, results, thresh=0.5):\n",
    "    \"\"\"\n",
    "    postprocess detection results\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    h, w: original height and width of input image\n",
    "    results: raw detection network output\n",
    "    thresh: threshold for low confidence filtering\n",
    "    \"\"\"\n",
    "    # The 'results' variable is a [1, 1, N, 7] tensor.\n",
    "    detections = results.reshape(-1, 7)\n",
    "    boxes = []\n",
    "    labels = []\n",
    "    scores = []\n",
    "    for i, detection in enumerate(detections):\n",
    "        _, label, score, xmin, ymin, xmax, ymax = detection\n",
    "        # Filter detected objects.\n",
    "        if score > thresh:\n",
    "            # Create a box with pixels coordinates from the box with normalized coordinates [0,1].\n",
    "            boxes.append(\n",
    "                [\n",
    "                    (xmin + xmax) / 2 * w,\n",
    "                    (ymin + ymax) / 2 * h,\n",
    "                    (xmax - xmin) * w,\n",
    "                    (ymax - ymin) * h,\n",
    "                ]\n",
    "            )\n",
    "            labels.append(int(label))\n",
    "            scores.append(float(score))\n",
    "\n",
    "    if len(boxes) == 0:\n",
    "        boxes = np.array([]).reshape(0, 4)\n",
    "        scores = np.array([])\n",
    "        labels = np.array([])\n",
    "    return np.array(boxes), np.array(scores), np.array(labels)\n",
    "\n",
    "\n",
    "def draw_boxes(img, bbox, identities=None):\n",
    "    \"\"\"\n",
    "    Draw bounding box in original image\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    img: original image\n",
    "    bbox: coordinate of bounding box\n",
    "    identities: identities IDs\n",
    "    \"\"\"\n",
    "    for i, box in enumerate(bbox):\n",
    "        x1, y1, x2, y2 = [int(i) for i in box]\n",
    "        # box text and bar\n",
    "        id = int(identities[i]) if identities is not None else 0\n",
    "        color = compute_color_for_labels(id)\n",
    "        label = \"{}{:d}\".format(\"\", id)\n",
    "        t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]\n",
    "        cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)\n",
    "        cv2.rectangle(img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1)\n",
    "        cv2.putText(\n",
    "            img,\n",
    "            label,\n",
    "            (x1, y1 + t_size[1] + 4),\n",
    "            cv2.FONT_HERSHEY_PLAIN,\n",
    "            1.6,\n",
    "            [255, 255, 255],\n",
    "            2,\n",
    "        )\n",
    "    return img\n",
    "\n",
    "\n",
    "def cosin_metric(x1, x2):\n",
    "    \"\"\"\n",
    "    Calculate the consin distance of two vector\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    x1, x2: input vectors\n",
    "    \"\"\"\n",
    "    return np.dot(x1, x2) / (np.linalg.norm(x1) * np.linalg.norm(x2))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test person reidentification model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The reidentification network outputs a blob with the `(1, 256)` shape named `reid_embedding`, which can be compared with other descriptors using the cosine distance."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualize data\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "base_file_link = \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/image/person_\"\n",
    "image_indices = [\"1_1.png\", \"1_2.png\", \"2_1.png\"]\n",
    "image_paths = [\n",
    "    utils.download_file(base_file_link + image_index, directory=\"data\") for image_index in image_indices if not (Path(\"data\") / image_index).exists()\n",
    "]\n",
    "image1, image2, image3 = [cv2.cvtColor(cv2.imread(str(image_path)), cv2.COLOR_BGR2RGB) for image_path in image_paths]\n",
    "\n",
    "# Define titles with images.\n",
    "data = {\"Person 1\": image1, \"Person 2\": image2, \"Person 3\": image3}\n",
    "\n",
    "# Create a subplot to visualize images.\n",
    "fig, axs = plt.subplots(1, len(data.items()), figsize=(5, 5))\n",
    "\n",
    "# Fill the subplot.\n",
    "for ax, (name, image) in zip(axs, data.items()):\n",
    "    ax.axis(\"off\")\n",
    "    ax.set_title(name)\n",
    "    ax.imshow(image)\n",
    "\n",
    "# Display an image.\n",
    "plt.show(fig)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compare two persons\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Metric parameters\n",
    "MAX_COSINE_DISTANCE = 0.6  # threshold of matching object\n",
    "input_data = [image2, image3]\n",
    "img_batch = batch_preprocess(input_data, extractor.height, extractor.width)\n",
    "features = extractor.predict(img_batch)\n",
    "sim = cosin_metric(features[0], features[1])\n",
    "if sim >= 1 - MAX_COSINE_DISTANCE:\n",
    "    print(f\"Same person (confidence: {sim})\")\n",
    "else:\n",
    "    print(f\"Different person (confidence: {sim})\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Main Processing Function\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Run person tracking on the specified source. Either a webcam feed or a video file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Main processing function to run person tracking.\n",
    "def run_person_tracking(source=0, flip=False, use_popup=False, skip_first_frames=0):\n",
    "    \"\"\"\n",
    "    Main function to run the person tracking:\n",
    "    1. Create a video player to play with target fps (utils.VideoPlayer).\n",
    "    2. Prepare a set of frames for person tracking.\n",
    "    3. Run AI inference for person tracking.\n",
    "    4. Visualize the results.\n",
    "\n",
    "    Parameters:\n",
    "    ----------\n",
    "        source: The webcam number to feed the video stream with primary webcam set to \"0\", or the video path.\n",
    "        flip: To be used by VideoPlayer function for flipping capture image.\n",
    "        use_popup: False for showing encoded frames over this notebook, True for creating a popup window.\n",
    "        skip_first_frames: Number of frames to skip at the beginning of the video.\n",
    "    \"\"\"\n",
    "    player = None\n",
    "    try:\n",
    "        # Create a video player to play with target fps.\n",
    "        player = utils.VideoPlayer(\n",
    "            source=source,\n",
    "            size=(700, 450),\n",
    "            flip=flip,\n",
    "            fps=24,\n",
    "            skip_first_frames=skip_first_frames,\n",
    "        )\n",
    "        # Start capturing.\n",
    "        player.start()\n",
    "        if use_popup:\n",
    "            title = \"Press ESC to Exit\"\n",
    "            cv2.namedWindow(winname=title, flags=cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)\n",
    "\n",
    "        processing_times = collections.deque()\n",
    "        while True:\n",
    "            # Grab the frame.\n",
    "            frame = player.next()\n",
    "            if frame is None:\n",
    "                print(\"Source ended\")\n",
    "                break\n",
    "            # If the frame is larger than full HD, reduce size to improve the performance.\n",
    "\n",
    "            # Resize the image and change dims to fit neural network input.\n",
    "            h, w = frame.shape[:2]\n",
    "            input_image = preprocess(frame, detector.height, detector.width)\n",
    "\n",
    "            # Measure processing time.\n",
    "            start_time = time.time()\n",
    "            # Get the results.\n",
    "            output = detector.predict(input_image)\n",
    "            stop_time = time.time()\n",
    "            processing_times.append(stop_time - start_time)\n",
    "            if len(processing_times) > 200:\n",
    "                processing_times.popleft()\n",
    "\n",
    "            _, f_width = frame.shape[:2]\n",
    "            # Mean processing time [ms].\n",
    "            processing_time = np.mean(processing_times) * 1100\n",
    "            fps = 1000 / processing_time\n",
    "\n",
    "            # Get poses from detection results.\n",
    "            bbox_xywh, score, label = process_results(h, w, results=output)\n",
    "\n",
    "            img_crops = []\n",
    "            for box in bbox_xywh:\n",
    "                x1, y1, x2, y2 = xywh_to_xyxy(box, h, w)\n",
    "                img = frame[y1:y2, x1:x2]\n",
    "                img_crops.append(img)\n",
    "\n",
    "            # Get reidentification feature of each person.\n",
    "            if img_crops:\n",
    "                # preprocess\n",
    "                img_batch = batch_preprocess(img_crops, extractor.height, extractor.width)\n",
    "                features = extractor.predict(img_batch)\n",
    "            else:\n",
    "                features = np.array([])\n",
    "\n",
    "            # Wrap the detection and reidentification results together\n",
    "            bbox_tlwh = xywh_to_tlwh(bbox_xywh)\n",
    "            detections = [Detection(bbox_tlwh[i], features[i]) for i in range(features.shape[0])]\n",
    "\n",
    "            # predict the position of tracking target\n",
    "            tracker.predict()\n",
    "\n",
    "            # update tracker\n",
    "            tracker.update(detections)\n",
    "\n",
    "            # update bbox identities\n",
    "            outputs = []\n",
    "            for track in tracker.tracks:\n",
    "                if not track.is_confirmed() or track.time_since_update > 1:\n",
    "                    continue\n",
    "                box = track.to_tlwh()\n",
    "                x1, y1, x2, y2 = tlwh_to_xyxy(box, h, w)\n",
    "                track_id = track.track_id\n",
    "                outputs.append(np.array([x1, y1, x2, y2, track_id], dtype=np.int32))\n",
    "            if len(outputs) > 0:\n",
    "                outputs = np.stack(outputs, axis=0)\n",
    "\n",
    "            # draw box for visualization\n",
    "            if len(outputs) > 0:\n",
    "                bbox_tlwh = []\n",
    "                bbox_xyxy = outputs[:, :4]\n",
    "                identities = outputs[:, -1]\n",
    "                frame = draw_boxes(frame, bbox_xyxy, identities)\n",
    "\n",
    "            cv2.putText(\n",
    "                img=frame,\n",
    "                text=f\"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)\",\n",
    "                org=(20, 40),\n",
    "                fontFace=cv2.FONT_HERSHEY_COMPLEX,\n",
    "                fontScale=f_width / 1000,\n",
    "                color=(0, 0, 255),\n",
    "                thickness=1,\n",
    "                lineType=cv2.LINE_AA,\n",
    "            )\n",
    "\n",
    "            if use_popup:\n",
    "                cv2.imshow(winname=title, mat=frame)\n",
    "                key = cv2.waitKey(1)\n",
    "                # escape = 27\n",
    "                if key == 27:\n",
    "                    break\n",
    "            else:\n",
    "                # Encode numpy array to jpg.\n",
    "                _, encoded_img = cv2.imencode(ext=\".jpg\", img=frame, params=[cv2.IMWRITE_JPEG_QUALITY, 100])\n",
    "                # Create an IPython image.\n",
    "                i = display.Image(data=encoded_img)\n",
    "                # Display the image in this notebook.\n",
    "                display.clear_output(wait=True)\n",
    "                display.display(i)\n",
    "\n",
    "    # ctrl-c\n",
    "    except KeyboardInterrupt:\n",
    "        print(\"Interrupted\")\n",
    "    # any different error\n",
    "    except RuntimeError as e:\n",
    "        print(e)\n",
    "    finally:\n",
    "        if player is not None:\n",
    "            # Stop capturing.\n",
    "            player.stop()\n",
    "        if use_popup:\n",
    "            cv2.destroyAllWindows()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "### Initialize tracker\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Before running a new tracking task, we have to reinitialize a Tracker object\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NN_BUDGET = 100\n",
    "MAX_COSINE_DISTANCE = 0.6  # threshold of matching object\n",
    "metric = NearestNeighborDistanceMetric(\"cosine\", MAX_COSINE_DISTANCE, NN_BUDGET)\n",
    "tracker = Tracker(metric, max_iou_distance=0.7, max_age=70, n_init=3)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run Live Person Tracking\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Use a webcam as the video input. By default, the primary webcam is set with `source=0`. If you have multiple webcams, each one will be assigned a consecutive number starting at 0. Set `flip=True` when using a front-facing camera. Some web browsers, especially Mozilla Firefox, may cause flickering. If you experience flickering, set `use_popup=True`.\n",
    "\n",
    "If you do not have a webcam, you can still run this demo with a video file. Any [format supported by OpenCV](https://docs.opencv.org/4.5.1/dd/d43/tutorial_py_video_display.html) will work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "USE_WEBCAM = False\n",
    "\n",
    "cam_id = 0\n",
    "video_url = \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/video/people.mp4\"\n",
    "video_file = Path(\"people.mp4\")\n",
    "source = cam_id if USE_WEBCAM else video_file\n",
    "\n",
    "if not USE_WEBCAM and not video_file.exists():\n",
    "    utils.download_file(video_url)\n",
    "\n",
    "run_person_tracking(source=source, flip=USE_WEBCAM, use_popup=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "openvino_notebooks": {
   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/person-tracking-webcam/person-tracking.gif?raw=true",
   "tags": {
    "categories": [
     "Live Demos"
    ],
    "libraries": [],
    "other": [],
    "tasks": [
     "Object Detection"
    ]
   }
  },
  "vscode": {
   "interpreter": {
    "hash": "1c707170576399eaaed0c4f2e01a2d1b61ba791ba1842c47e5b3e4f6f79b82ab"
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
